package com.gugee.ins.data.analysis.service.impl;


import com.gugee.common.thread.ScheduleTemplate;
import com.gugee.ins.common.constant.InsBloggerMsgTypeCodeEnum;
import com.gugee.ins.common.dal.service.blogger.InsBloggerDao;
import com.gugee.ins.common.dal.service.blogger.InsBloggerMainDao;
import com.gugee.ins.common.dal.service.dic.InsDicLocationDao;
import com.gugee.ins.common.model.mysql.blogger.InsBlogger;
import com.gugee.ins.data.analysis.config.InsAnalysisConfig;
import com.gugee.ins.data.analysis.service.InsAnalysisLocationService;
import com.gugee.ins.data.common.msg.InsBloggerMessage;
import com.xiguaji.boot.toolkit.ThreadPoolUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.ForkJoinPool;

/**
 * insBloggerLocation 服务
 * @author Huangxin
 */
@Slf4j
@Service
public class InsAnalysisLocationServiceImpl implements InsAnalysisLocationService {

    /**
     * 配置
     */
    @Autowired
    InsAnalysisConfig insAnalysisConfig;

    /**
     * 线程调度
     */
    @Autowired
    ScheduleTemplate scheduleTemplate;

    /**
     * InsDicLocationDao
     */
    @Autowired
    InsDicLocationDao insDicLocationDao;

    /**
     * InsBloggerDao
     */
    @Autowired
    InsBloggerDao insBloggerDao;

    /**
     * InsBloggerDao
     */
    @Autowired
    InsBloggerMainDao insBloggerMainDao;

    /**
     * kafkaTemplate
     */
    @Autowired
    KafkaTemplate<Long,InsBloggerMessage> kafkaTemplateInsAnalysisAvatar;

    /**
     * 线程池
     */
    ForkJoinPool forkJoinPool;

    /**
     * 线程名
     */
    private String workName = "insAnalysisLocation-worker";

    /**
     * 初始化线程池
     */
    @PostConstruct
    public void init() {
        forkJoinPool = ThreadPoolUtils.forkJoinPool(insAnalysisConfig.getInsAnalysisLocationCorePollSize(), workName);
        scheduleTemplate.attach(workName, forkJoinPool);
    }

    /**
     * 处理 分析地点 任务
     * @param insBloggerMessages
     */
    @Override
    public void handleAnalysisLocation(List<InsBloggerMessage> insBloggerMessages) {
        try {
            forkJoinPool.submit(() -> insBloggerMessages.parallelStream().forEach(msg -> {
                try {
                    // 分析地点
                    analysisLocation(msg);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    log.error("insAnalysisNation error. uid:{}, error :{}" ,
                            msg.getUid(),ex.getMessage());
                }
            })).get();
        } catch (Exception ex) {
            log.error("insAnalysisNation thread error.  {}" ,  ex.getMessage());
        }
    }

    /**
     * 分析地点
     *
     * @param insBloggerMessage
     */
    public void analysisLocation(InsBloggerMessage insBloggerMessage){
        long start = System.currentTimeMillis();
        long uid = insBloggerMessage.getUid();

        // 时间范围
        long limitTime = System.currentTimeMillis() / 1000 - insAnalysisConfig.getInsAnalysisNationIntervalDay() * 24 * 3600;

        // 判断类型是否需要分析大博主地理位置
        if(insBloggerMessage.getTypeCode() != InsBloggerMsgTypeCodeEnum.NO_HANDLE_AND_DO_OTHER_OPT.getCode()){
            try{
                analysisLocation(uid);
            }catch (Exception e){
                log.error(" insMainBlogger insAnalysisNation error. uid:{}, error :{}",uid,e.getMessage());
            }
        }

        List<InsBloggerMessage> subMessages = insBloggerMainDao.findInsAnalysisNationMessageByUid(insBloggerMessage.getUid(),limitTime);
        if(subMessages != null && !subMessages.isEmpty()){
            try {
                forkJoinPool.submit(() -> subMessages.parallelStream().forEach(msg -> {
                    try{
                        analysisLocation(msg.getUid());
                    }catch (Exception e){
                        log.error("subInsBlogger sub insAnalysisNation collect error. uid:{}, error :{}",msg.getUid(),e.getMessage());
                    }
                })).get();
            } catch (Exception ex) {
                log.error("subInsBlogger insAnalysisNation thread error.  {}" ,  ex.getMessage());
            }

            // 发送优先统计国家
            sendPriorityStMsg(insBloggerMessage);
        }
        if ((System.currentTimeMillis() - start) / 1000 > insAnalysisConfig.getInsAnalysisLocationDebugTimeLimit()) {
            log.info("insAnalysisAvatar uid:{} use time:{}s", insBloggerMessage.getUid(),(System.currentTimeMillis() - start) / 1000);
        }
    }

    /**
     * 分析地点
     *
     * @param uid
     */
    public void analysisLocation(long uid){
        String nation = "";
        String region = "";
        List<String> nations;
        int nationSource = 0;
        InsBlogger insBlogger = insBloggerDao.findByUid(uid);

        if(insBlogger != null){
            // 根据uid接口获取的 cityName 分析国家
            if(!StringUtils.isEmpty(insBlogger.getCityName())){
                region = insBlogger.getCityName().substring(insBlogger.getCityName().lastIndexOf(",") + 1).trim();
                nations = insDicLocationDao.findNationByRegion(region);
                if(nations != null && !nations.isEmpty()){
                    nation = nations.get(0);
                    nationSource = 1;
                }
            }

            // 根据detail接口获取的 cityName 分析国家
            if(StringUtils.isEmpty(nation)
                    && !StringUtils.isEmpty(insBlogger.getDetailCityName())){
                region = insBlogger.getDetailCityName().substring(insBlogger.getDetailCityName().lastIndexOf(",") + 1).trim();
                nations = insDicLocationDao.findNationByRegion(region);
                if(nations != null && !nations.isEmpty()){
                    nation = nations.get(0);
                    nationSource = 2;
                }
            }

            // 根据帖子中获取的 locationName 分析国家
            if(StringUtils.isEmpty(nation)){
                nations = insDicLocationDao.findNationByUid(uid);
                if(nations != null && !nations.isEmpty()){
                    nation = nations.get(0);
                    nationSource = 3;
                }
            }

            // 保存
            saveAnalysisLocation(uid,nation,nationSource);
        }
    }

    /**
     * 保存
     * @param uid
     * @param nation
     * @param nationSource
     */
    public void saveAnalysisLocation(long uid,String nation,int nationSource){
        if(nationSource != 0){
            //更新数据库 blogger
            insBloggerDao.updateNation(uid,nation,nationSource);
            //更新数据库 blogger_main
            insBloggerMainDao.updateNation(uid,nation,nationSource);
        }
    }

    /**
     * 发送优先统计语言的消息
     * @param insBloggerMessage
     */
    public void sendPriorityStMsg(InsBloggerMessage insBloggerMessage){
        insBloggerMessage.setTypeCode(InsBloggerMsgTypeCodeEnum.ST_NATION.getCode());
        insBloggerMessage.setRetryTimes(insAnalysisConfig.getInsMBloggerActiveFollowerDataStPriorityRetryTimes());
        insBloggerMessage.setRetryLimitTimes(insAnalysisConfig.getInsMBloggerActiveFollowerDataStPriorityRetryTimes());
        insBloggerMessage.setEventTime(System.currentTimeMillis());
        kafkaTemplateInsAnalysisAvatar.send(insAnalysisConfig.getInsMBloggerActiveFollowerDataStPriorityTopic(),insBloggerMessage);
    }
}
